package com.example.lotapp;

import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import android.app.Application;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.text.TextUtils;

import com.example.lotapp.network.ParamUtils;
import com.example.lotapp.utils.PhoneInfo;

public class AppContext extends Application {
	private static AppContext singleInstance;
	public static AppContext getInstance() {
		return singleInstance;
	}
	
	@Override
	public void onCreate() {
		singleInstance = this;
		
		initVersion();
		initChannelInfo();
		
		PhoneInfo phoneInfo = new PhoneInfo(this);
		ParamUtils.setUuid(phoneInfo.getIme());
	}
	
	
	/**
	 * channelFileName = "jddchannel__0__app_zz"
	 */
	public void initChannelInfo() {
	    ApplicationInfo appInfo = getInstance().getApplicationInfo();
	    String channelFileName = "";
	    ZipFile zipFile = null;
	    try {
	        zipFile = new ZipFile(appInfo.sourceDir);
	        Enumeration<?> entries = zipFile.entries();
	        while (entries.hasMoreElements()) {
	            ZipEntry entry = ((ZipEntry) entries.nextElement());
	            String entryName = entry.getName();
	            if (entryName.contains("jddchannel__")) {
	                channelFileName = entryName;
	                break;
	            }
	        }
	    } catch (Exception e) {

	    } finally {
	        if (zipFile != null) {
	            try {
	                zipFile.close();
	            } catch (Exception e) {
	            }
	        }
	    }

	    int channelId = 0;
        String channelName = "app_zz";
        
	    if (!TextUtils.isEmpty(channelFileName)) {
	        String[] split = channelFileName.split("__");
	        if (split != null && split.length >= 3) {
	            try {
	                channelId = Integer.parseInt(split[1].trim());
	            } catch (Exception e) {
	            }
	            channelName = split[2].trim();
	        }
	    }
	    
	    ApplicationData.getInstance().setChannelNumber(channelId);
        ApplicationData.getInstance().setChannelName(channelName);
	}
	
	public void initVersion() {
		PackageManager packageManager = getPackageManager();
		try {
			PackageInfo packageInfo = packageManager.getPackageInfo(getPackageName(), 0);
			ApplicationData.getInstance().setAppVerName(packageInfo.versionName);
			ApplicationData.getInstance().setAppVerCode(packageInfo.versionCode);
		} catch (NameNotFoundException e) {
		}
	}
}
